package com.jishuo.nontax.bfc.service;

import com.github.pagehelper.PageHelper;
import com.jishuo.base.bean.BaseResult;
import com.jishuo.base.bean.ErrorCodeEnum;
import com.jishuo.base.bean.Pagination;
import com.jishuo.base.bean.vo.UserVO;
import com.jishuo.base.config.NonTaxConfig;
import com.jishuo.base.dao.UserMapper;
import com.jishuo.base.service.SequenceService;
import com.jishuo.base.util.ExportSXSSFUtil;
import com.jishuo.base.util.MD5;
import com.jishuo.nontax.bean.bank.IllegalactivityScaleDetail;
import com.jishuo.nontax.bean.bank.IllegalactivityScaleinfo;
import com.jishuo.nontax.bean.message.SetBankIllegalactivityScaleinfo;
import com.jishuo.nontax.bean.message.SetBankIllegalactivityScaleinfoBackOut;
import com.jishuo.nontax.bean.message.SetIllegalactivityScaleinfo;
import com.jishuo.nontax.bean.vo.BankStationVO;
import com.jishuo.nontax.bean.vo.BankVO;
import com.jishuo.nontax.bean.vo.PayScaleBillVO;
import com.jishuo.nontax.bfc.dao.BankMapper;
import com.jishuo.nontax.bfc.dao.BaseDataMapper;
import com.jishuo.nontax.bfc.dao.PayScaleBillMapper;
import com.jishuo.nontax.bfc.pzk.PzkService;
import com.jishuo.nontax.bfc.tlq.MessageFactory;
import com.jishuo.nontax.bfc.tlq.MessageService;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @auther dinggaofei
 * @Date 2023/2/3 9:24
 */
@Service
public class PayScaleBillService {

    private static Logger logger = LoggerFactory.getLogger(EticketNumService.class);

    @Resource
    private PayScaleBillMapper payScaleBillMapper;
    @Resource
    private SequenceService sequenceService;
    @Resource
    private MessageService messageService;
    @Resource
    private NonTaxConfig nonTaxConfig;
    @Resource
    private BankMapper bankMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private BaseDataMapper baseDataMapper;

    /**
     * @param billnum 单据号
     * @auther dinggaofei
     * @Date 2022/12/23 16:26
     * @description 获取交管二八分成单据
     */
    public BaseResult getIllegalactivityScale(String billnum) {
        //根据缴费码从本地获取交管二八分成数据
        PayScaleBillVO bill = payScaleBillMapper.findIllScaleInfo(billnum);

        //xml解析器
        Serializer serializer = new Persister();
        //xml转换器
        StringWriter sw = new StringWriter();

        try {
            BaseResult ret = new BaseResult();
            // 已缴费的直接返回
            if (bill != null && Integer.valueOf(1).equals(bill.getIsbankaffirm())) {
                IllegalactivityScaleinfo info = bill.getIllegalactivityScale();
                ArrayList<IllegalactivityScaleDetail> scaleDetail = payScaleBillMapper.findIllScaleDetail(billnum);
                info.setDetail(scaleDetail);
                info.setBillnum(billnum);
                info.setBillstate("3");
                serializer.write(info, sw);
                ret.setData(sw.toString());
                return ret;
            }
            //获取messageid
            long messageid = sequenceService.getNextSeq("ELEMESSAGESEQ");
            // 从财政查询
            boolean suc = messageService.sendAndRecvMessage("GETILLEGALACTIVITYSCALEINFO", messageid, MessageFactory.getIllegalactivityScale(billnum), "2.0");
            if (suc) {
                bill = payScaleBillMapper.findIllScaleInfo(billnum);
                IllegalactivityScaleinfo info = bill.getIllegalactivityScale();
                ArrayList<IllegalactivityScaleDetail> scaleDetail = payScaleBillMapper.findIllScaleDetail(billnum);
                info.setDetail(scaleDetail);
                serializer.write(info, sw);
                ret.setData(sw.toString());
                return ret;
            }
            return null;
        } catch (Exception ex) {
            logger.info("失败：" + ex.toString());
            return null;
        }
    }

    /**
     * @param billnum 票据号
     * @auther dinggaofei
     * @Date 2022/12/27  14:30
     * @description 交管二八分成缴费信息
     */
    public int sendIllegalactivityScaleBankaffirm(String billnum) {

        PayScaleBillVO payScaleBill = payScaleBillMapper.findIllScaleSend(billnum, null);
        //xml解析器
        Serializer serializer = new Persister();
        //xml转换器
        StringWriter sw = new StringWriter();

        if (payScaleBill == null) {
            return 0;
        } else {
            long messageid = 0;
            try {
                messageid = sequenceService.getNextSeq("ELEMESSAGESEQ");
            } catch (Exception e) {
                return 0;
            }

            try {
                Object obj = MessageFactory.sendIllegalactivityScaleBankaffirm(payScaleBill);
                boolean suc = messageService.sendMessage("SETBANKILLEGALACTIVITYSCALEINFO", messageid, obj, "2.0");
                if (suc) {
                    SetBankIllegalactivityScaleinfo info;
                    info = payScaleBill.findIllScaleSend();
                    serializer.write(info, sw);
                    return 1;
                }
                // 写凭证
                if (nonTaxConfig.IS_Pzk) {
                    PzkService.sendPzk("SETBANKILLEGALACTIVITYSCALEINFOPZK", obj);
                }
            } catch (Exception e) {
                logger.info("失败：" + e.toString());
                return 0;
            }


        }
        return 0;
    }

    /**
     * @param payScaleBillVO 交管二八分成对象
     * @auther dinggaofei
     * @Date 2023/1/12  15:33
     * @description 交管二八分成单据付款信息
     */
    public BaseResult setIllegalactivityScaleBankaffirm(PayScaleBillVO payScaleBillVO) {

        //xml解析器
        Serializer serializer = new Persister();
        //xml转换器
        StringWriter sw = new StringWriter();
        String wtime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        payScaleBillVO.setSendtime(wtime);
        long messageid = 0;
        try {
            messageid = sequenceService.getNextSeq("ELEMESSAGESEQ");
        } catch (Exception e) {
            return new BaseResult(ErrorCodeEnum.DB_ERR);
        }
        payScaleBillVO.setMessageid(messageid);

        int i = payScaleBillMapper.updateIllSacleBankAffirm(payScaleBillVO);
        try {
            BaseResult result = new BaseResult();

            if (i > 0) {
                Object obj = MessageFactory.sendIllegalactivityScaleBankaffirm(payScaleBillVO);
                boolean suc = messageService.sendMessage("SETBANKILLEGALACTIVITYSCALEINFO", messageid, obj, "2.0");
                if (suc) {
                    SetBankIllegalactivityScaleinfo info;
                    info = payScaleBillVO.findIllScaleSend();
                    serializer.write(info, sw);
                    result.setData(info);
                    return result;
                }
                // 写凭证
                if (nonTaxConfig.IS_Pzk) {
                    PzkService.sendPzk("SETETICKETNUMDEPOSITPZK", obj);
                }
            } else {

                return new BaseResult(ErrorCodeEnum.DB_ERR);
            }
        } catch (Exception e) {
            logger.info("失败：" + e.toString());
            return new BaseResult(ErrorCodeEnum.SYS_ERR);
        }
        return new BaseResult();

    }

    public void setIllegalactivityScale(String data) {
        try {
            //xml解析器
            Serializer serializer = new Persister();
            //返回交管二八分成缴款书对象
            SetIllegalactivityScaleinfo sacle = new SetIllegalactivityScaleinfo();
            serializer.read(SetBankIllegalactivityScaleinfo.class, new StringReader(data));
            PayScaleBillVO payScaleBillVO = new PayScaleBillVO(sacle);
            BankVO bankVO = bankMapper.findBankVO(payScaleBillVO.getAccountcode());
            payScaleBillVO.setIssend(2);
            payScaleBillVO.setBankid(bankVO.getBankid());
            if (payScaleBillMapper.findCountBybillnoAndBillnum(payScaleBillVO.getBillno(), payScaleBillVO.getBillnum()) > 0) {
                payScaleBillMapper.updateIllSacle(payScaleBillVO);
            } else {
                long bankid = sequenceService.getNextSeq("FSPAYDIVIDESEQ");
                sacle.setBankid(String.valueOf(bankid));
                payScaleBillMapper.insertIllSacle(payScaleBillVO);
            }

        } catch (Exception e) {
            logger.info("失败：" + e.toString());
        }

    }

    /**
     * 交管二八分成列表
     *
     * @param payScaleBillVO
     * @param pagination
     * @return
     */
    public List<PayScaleBillVO> listPayScale(PayScaleBillVO payScaleBillVO, Pagination pagination) {
        if (pagination.getRows() > 0) PageHelper.startPage(pagination.getPage(), pagination.getRows());
        return this.payScaleBillMapper.findPayScalPage(payScaleBillVO);
    }

    /**
     * 修改交管二八分成银行信息
     *
     * @param payScaleBillVO
     * @return
     */

    public BaseResult saveIllAgeScale(PayScaleBillVO payScaleBillVO) {

        int ret = payScaleBillMapper.saveIllAgeScale(payScaleBillVO);

        if (ret < 1) return new BaseResult(ErrorCodeEnum.DB_ERR);
        return new BaseResult();
    }

    public PayScaleBillVO getPayScale(Long payscalebillid) {

        PayScaleBillVO payScaleBillVO = payScaleBillMapper.getPayScale(payscalebillid);
        return payScaleBillVO;
    }

    private BaseResult sendIllegalactivityScale(PayScaleBillVO vos) {


        //xml解析器
        Serializer serializer = new Persister();
        //xml转换器
        StringWriter sw = new StringWriter();
        int i = payScaleBillMapper.updateIllSacleBankAffirm(vos);
        try {
            long messageid = sequenceService.getNextSeq("ELEMESSAGESEQ");
            if (i > 0) {
                SetBankIllegalactivityScaleinfo setBankIllegalactivityScaleinfo = vos.getSetBankIllegalactivityScaleinfo();
                serializer.write(setBankIllegalactivityScaleinfo, sw);
                messageService.sendMessage("SETBANKILLEGALACTIVITYSCALEINFO", messageid, setBankIllegalactivityScaleinfo, "2.0");
                if (nonTaxConfig.IS_Pzk) {
                    PzkService.sendPzk("SETBANKILLEGALACTIVITYSCALEINFOPZK", setBankIllegalactivityScaleinfo);
                }
                return new BaseResult();
            } else {
                return new BaseResult(ErrorCodeEnum.DB_ERR);
            }
        } catch (Exception e) {
            logger.info("失败：" + e.toString());

        }
        return new BaseResult();
    }

    /**
     * 发送交管二八分成
     *
     * @param billids
     * @param userpwd
     * @param usercode
     * @return
     */
    public BaseResult sendPayScale(List<String> billids, String userpwd, String usercode) {
        userpwd = (new MD5().md5s(userpwd));
        if (userMapper.getUserCount(userpwd, usercode) > 0) {
            if (billids != null && billids.size() > 0 ) {
                List<PayScaleBillVO> payScalPage = payScaleBillMapper.findPayScal(billids);

                for (PayScaleBillVO vos : payScalPage
                ) {
                    return sendIllegalactivityScale(vos);
                }
            } else {
                return new BaseResult(ErrorCodeEnum.BILL_NOT_FOUND);
            }
        } else {
            return new BaseResult(ErrorCodeEnum.CUSTOM_ERR.getCode(), "用户信息验证失败");
        }

        return new BaseResult(ErrorCodeEnum.UNKNOWN_ERR);
    }

    private BaseResult setIllegalactivityScaleBackOut(PayScaleBillVO vos) {
        SetBankIllegalactivityScaleinfoBackOut setBankIllegalactivityScaleinfoBackOut = vos.getSetBankIllegalactivityScaleinfoBackOut();
        setBankIllegalactivityScaleinfoBackOut.setRemark("");
        setBankIllegalactivityScaleinfoBackOut.setBackoutname("");
        if (nonTaxConfig.IS_Pzk) {
            PzkService.sendPzk("SETBANKILLEGALACTIVITYSCALEINFOBACKOUTPZK", setBankIllegalactivityScaleinfoBackOut);
            return new BaseResult();
        }
        try {
            long messageid = sequenceService.getNextSeq("ELEMESSAGESEQ");
            messageService.sendMessage("", messageid, setBankIllegalactivityScaleinfoBackOut, "2.0");
        } catch (Exception e) {
            logger.info("失败：" + e.toString());
            return new BaseResult(ErrorCodeEnum.TLQ_ERR);
        }
        return new BaseResult();
    }

    /**
     * 冲销交管二八分成
     *
     * @param billids
     * @param userpwd
     * @param usercode
     * @return
     */

    public BaseResult cleanPayScale(List<String> billids, String userpwd, String usercode) {
        String errinfo = "";
        try {
            userpwd = (new MD5().md5s(userpwd));
            if (userMapper.getUserCount(userpwd, usercode) > 0) {
                if (billids != null && billids.size() >0 ) {
                    PayScaleBillVO vo = new PayScaleBillVO();
                    List<PayScaleBillVO> payScalPage = payScaleBillMapper.findPayScal(billids);
                    for (PayScaleBillVO vos : payScalPage
                    ) {
                        if (vos.getSendtime().equals("")) {
                            setIllegalactivityScaleBackOut(vos);
                            payScaleBillMapper.updateIsBankAffirm(vos.getPayscalebillid());

                        } else {
                            Date date = new Date();
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            Date date2 = sdf.parse(vos.getSendtime());
                            long temp = date.getTime() - date2.getTime();    //相差毫秒数
                            long hours = temp / 1000 / 3600;                //相差小时数
                            long temp2 = temp % (1000 * 3600);
                            long mins = temp2 / 1000 / 60;                    //相差分钟数
                            if (((hours * 60) + mins) < (nonTaxConfig.CxTime)) {
                                setIllegalactivityScaleBackOut(vos);
                                payScaleBillMapper.updateIsBankAffirm(vos.getPayscalebillid());
                            } else {
                                errinfo += vos.getBillnum();
                            }
                        }
                    }
                    if (!errinfo.equals("")) {
                        errinfo = errinfo.substring(0, errinfo.length() - 1) + "超时冲销失败,其他单据冲销成功!";
                        return new BaseResult(ErrorCodeEnum.CUSTOM_ERR.getCode(), errinfo);
                    } else {
                        errinfo = "冲销成功";
                        return new BaseResult(ErrorCodeEnum.SUCCESS.getCode(), errinfo);
                    }
                } else {
                    return new BaseResult(ErrorCodeEnum.CUSTOM_ERR.getCode(), "单号不存在");
                }
            } else {
                return new BaseResult(ErrorCodeEnum.CUSTOM_ERR.getCode(), "用户信息验证失败");
            }
        } catch (Exception e) {
            return new BaseResult(ErrorCodeEnum.UNKNOWN_ERR);
        }
    }


    public void scaleBillExport(List<String> billids , HttpServletResponse response) {
        List<PayScaleBillVO> payScalPage = payScaleBillMapper.findPayScal(billids);
        String[] headers = {"流水号", "单据号", "划款银行id", "银行名称", "账户", "账号", "单据内编码", "收款人区划id", "收款人区划编码", "收款人区划名称", "收款人银行id", "收款人银行名称", "收款人账户名称", "收款人账号", "金额", "交易日期", "银行交易流水号", "银行网点", "单据状态", "发送时间", "__status", "银行核心交易流水号", "是否发送"};
        String[] col = {"payscalebillid", "billnum", "payerbankid", "payeraccountname", "payerbankname", "payeraccountcode", "billno", "cantonid", "cantoncode", "cantonname", "payeebankid", "payeebankname", "payeeaccountname", "payeeaccountcode", "funds", "paybankdt", "bankaffirm", "bankstation", "billstate", "sendtime", "", "hxbankaffirm", "issend"};
        ExportSXSSFUtil ex = new ExportSXSSFUtil();
        SXSSFWorkbook workbook = ex.exportExcelSXSSF("国库单据列表", headers, col, payScalPage, null);
        response.setContentType("application/vnd.ms-excel");
        try {
            response.setHeader("Content-Disposition", "attachment;filename=" +
                    new String(("国库单据.xls").getBytes(), "iso-8859-1"));
            OutputStream ouputStream = response.getOutputStream();
            workbook.write(ouputStream);
            ouputStream.flush();
            ouputStream.close();
        } catch (Exception e) {
            logger.info("导出失败：" + e.toString());
        }
    }

    /**
     * 交管二八分成柜面付款
     *
     * @param payScaleBillVO
     * @param user
     * @return
     */
    public BaseResult scalebillPay(PayScaleBillVO payScaleBillVO, UserVO user) {
        PayScaleBillVO illScaleSend = payScaleBillMapper.findIllScaleSend(payScaleBillVO.getBillnum(), payScaleBillVO.getBillno());
        if (illScaleSend != null) {
            return new BaseResult(ErrorCodeEnum.BILL_PAYED);
        }
        CommBankService cbs = new CommBankService();
        //通过银行接口或者session中提取银行核心参数hx_paybankdt，hx_bankaffirm,bankstation
        Map<String, String> rtnBank = cbs.processIllegalactivityDividePay();
        //获取银行返回数据
        String paybankdt = rtnBank.get("hx_paybankdt");
        payScaleBillVO.setBankaffirm(rtnBank.get("hx_bankaffirm"));
        payScaleBillVO.setBankstation(rtnBank.get("bankstation"));
        //转换银行编码
        BankStationVO bankStationVO = baseDataMapper.getBankStation(user.getBankStationId());
        payScaleBillVO.setPaybankdt(paybankdt);
        payScaleBillVO.setBankstation(bankStationVO.getBankstationcode());
        payScaleBillVO.setIsbankaffirm(0);
        BaseResult baseResult = setIllegalactivityScaleBankaffirm(payScaleBillVO);
        if (baseResult.isSuccess()) {
            payScaleBillVO.setBillnum(payScaleBillVO.getBillnum());
            payScaleBillVO.setHxbankaffirm(payScaleBillVO.getBankaffirm());
            payScaleBillMapper.updateIllSacleHxBankaffirm(payScaleBillVO);
        }
        return baseResult;
    }
}


